<template>
  <el-container>
    <el-main>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card>
            <div id="flight-income-chart" style="width: 100%; height: 400px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div id="hotel-income-chart" style="width: 100%; height: 400px;"></div>
          </el-card>

        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card>
            <div id="tourism-chart" style="width: 100%; height: 400px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div id="tourism-pie-chart" style="width: 100%; height: 400px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script setup>
import { onMounted } from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import { getOrderList } from '@/api/order';
import { listHotelOrders } from '@/api/hotelOrder';

// 生成戏剧性数据
const generateDramaticData = () => {
  const regions = ['北京', '上海', '广州', '深圳', '杭州', '成都', '重庆', '南京', '武汉', '西安'];
  const years = Array.from({ length: 11 }, (_, i) => 2014 + i);
  const data = [];

  years.forEach(year => {
    regions.forEach(region => {
      data.push([Math.floor(Math.random() * 5000 + 5000), year, region]);
    });
  });

  return data;
};

// 生成旅游城市数据
const generateTourismPieData = (count) => {
  const cities = ['哈尔滨', '长春', '沈阳', '天津', '济南', '青岛', '郑州', '合肥', '福州', '南昌', '长沙', '南宁', '海口', '贵阳', '昆明', '拉萨', '兰州', '西宁', '银川', '乌鲁木齐'];
  const data = [];
  const usedCities = new Set();

  while (data.length < count) {
    const city = cities[Math.floor(Math.random() * cities.length)];
    if (!usedCities.has(city)) {
      usedCities.add(city);
      data.push({
        name: city,
        value: Math.floor(Math.random() * 100000 + 1000),
      });
    }
  }

  return data;
};

const formatDate = (date) => {
  const d = new Date(date);
  return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
};

const processData = (data, dateKey, valueKey) => {
  const dailyIncome = {};

  data.forEach(order => {
    const date = formatDate(order[dateKey]);
    if (!dailyIncome[date]) {
      dailyIncome[date] = 0;
    }
    dailyIncome[date] += Number(order[valueKey]);
  });

  const dates = Object.keys(dailyIncome).sort();
  const values = dates.map(date => dailyIncome[date]);

  return { dates, values };
};

const initChart = (domId, title, dates, values) => {
  var chartDom = document.getElementById(domId);
  var myChart = echarts.init(chartDom);
  var option = {
    visualMap: [
      {
        show: false,
        type: 'continuous',
        seriesIndex: 0,
        min: 0,
        max: Math.max(...values),
      },
    ],
    title: {
      left: 'center',
      text: title,
    },
    tooltip: {
      trigger: 'axis',
    },
    xAxis: {
      type: 'category',
      data: dates,
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        type: 'line',
        showSymbol: false,
        data: values,
      },
    ],
  };
  option && myChart.setOption(option);
};

const initTourismChart = (data) => {
  var chartDom = document.getElementById('tourism-chart');
  var myChart = echarts.init(chartDom);
  const years = Array.from({ length: 11 }, (_, i) => 2014 + i);
  let startYear = years[0];
  const option = {
    grid: {
      top: 10,
      bottom: 30,
      left: 150,
      right: 80,
    },
    xAxis: {
      max: 'dataMax',
      axisLabel: {
        formatter: function (n) {
          return Math.round(n) + '';
        },
      },
    },
    dataset: {
      source: data.filter(d => d[1] === startYear),
    },
    yAxis: {
      type: 'category',
      inverse: true,
      max: 10,
      axisLabel: {
        show: true,
        fontSize: 14,
        formatter: function (value) {
          return value;
        },
      },
      animationDuration: 300,
      animationDurationUpdate: 300,
    },
    series: [
      {
        realtimeSort: true,
        seriesLayoutBy: 'column',
        type: 'bar',
        itemStyle: {
          color: '#5470c6',
        },
        encode: {
          x: 0,
          y: 2,
        },
        label: {
          show: true,
          precision: 1,
          position: 'right',
          valueAnimation: true,
          fontFamily: 'monospace',
        },
      },
    ],
    animationDuration: 0,
    animationDurationUpdate: 2000,
    animationEasing: 'linear',
    animationEasingUpdate: 'linear',
    graphic: {
      elements: [
        {
          type: 'text',
          right: 160,
          bottom: 60,
          style: {
            text: startYear,
            font: 'bolder 80px monospace',
            fill: 'rgba(100, 100, 100, 0.25)',
          },
          z: 100,
        },
      ],
    },
  };

  myChart.setOption(option);

  for (let i = 0; i < years.length - 1; ++i) {
    (function (i) {
      setTimeout(function () {
        updateYear(years[i + 1]);
      }, i * 2000);
    })(i);
  }

  function updateYear(year) {
    let source = data.filter(d => d[1] === year);
    option.series[0].data = source;
    option.graphic.elements[0].style.text = year;
    myChart.setOption(option);
  }
};

const initTourismPieChart = (data) => {
  var chartDom = document.getElementById('tourism-pie-chart');
  var myChart = echarts.init(chartDom);
  var option = {
    title: {
      text: '中国旅游城市出行统计',
      subtext: '纯属虚构',
      left: 'center',
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)',
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 20,
      bottom: 20,
      data: data.map(item => item.name),
    },
    series: [
      {
        name: '城市',
        type: 'pie',
        radius: '55%',
        center: ['40%', '50%'],
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };
  option && myChart.setOption(option);
};

onMounted(async () => {
  try {
    const flightResponse = await getOrderList();
    const hotelResponse = await listHotelOrders();

    if (flightResponse.code === 1) {
      const { dates: flightDates, values: flightValues } = processData(flightResponse.data, 'orderTime', 'tprice');
      initChart('flight-income-chart', '每日航班收入', flightDates, flightValues);
    } else {
      ElMessage.error('获取航班订单数据失败');
    }

    if (hotelResponse.code === 1) {
      const { dates: hotelDates, values: hotelValues } = processData(hotelResponse.data, 'tftime', 'price');
      initChart('hotel-income-chart', '每日酒店收入', hotelDates, hotelValues);
    } else {
      ElMessage.error('获取酒店订单数据失败');
    }

    // 初始化旅游柱状图
    const tourismData = generateDramaticData();
    initTourismChart(tourismData);

    // 初始化旅游饼状图
    const tourismPieData = generateTourismPieData(20);
    initTourismPieChart(tourismPieData);
  } catch (error) {
    ElMessage.error('数据加载失败');
  }
});
</script>

<style scoped>
.el-header {
  background-color: #b3c0d1;
  color: #333;
  text-align: center;
  line-height: 60px;
}
.el-aside {
  background-color: #d3dce6;
  text-align: center;
  line-height: 200px;
}
.el-main {
  background-color: white;
  text-align: center;
  line-height: 160px;
}
.el-footer {
  background-color: #f5f5f5;
  text-align: center;
  line-height: 60px;
}
</style>
